package com.ljh.advance.c1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * @author: Themberfue
 * @date: 2025/5/28 17:45
 * @description:
 */
public class Client4 {
    public static void main(String[] args) {
        send();
        System.out.println("finish...");
    }

    private static String makeString(char ch, int i) {
        return String.valueOf(ch).repeat(i) + "!@";
    }

    private static void send() {
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(worker);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    // ! 服务端配置自定义结尾符号，客户端也需要配置
                    ByteBuf delimiter1 = ch.alloc().buffer(1).writeByte('!');
                    ByteBuf delimiter2 = ch.alloc().buffer(1).writeByte('@');
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter1, delimiter2));
                    ch.pipeline().addLast(new LoggingHandler());
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override // ? 会话在建立连接后，就会触发 active 事件，进而执行该方法
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ByteBuf buf = ctx.alloc().buffer();
                            Random r = new Random();
                            char ch = 'a';
                            for (int i = 0; i < 10; i++) {
                                String str = makeString(ch, r.nextInt(256) + 1);
                                buf.writeBytes(str.getBytes());
                                ch++;
                            }
                            ctx.writeAndFlush(buf);
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
